package com.wzb.mybatisplus.bitaction.electrumaction.btc01;

import com.wzb.mybatisplus.bitaction.BitcoinPrivateKeyGenerator1;
import com.wzb.mybatisplus.bitaction.electrumaction.one.BitcoinKeyConverter;
import com.wzb.mybatisplus.bitaction.electrumaction.one.BlockchainBalanceChecker;
import com.wzb.mybatisplus.bitaction.electrumaction.one.KeyPair;
import com.wzb.mybatisplus.bitaction.electrumaction.three.SendEmailToQQ;
import com.wzb.mybatisplus.entity.Bituse;
import lombok.extern.slf4j.Slf4j;
import org.bitcoinj.core.*;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.script.Script;
import org.bitcoinj.script.ScriptBuilder;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Slf4j
public class test {
//Gx: 79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798
//
//Gy: 483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8
private static final NetworkParameters MAINNET = MainNetParams.get();
    public static String wifToDecimal(String wif) {
        try {
            NetworkParameters params = MainNetParams.get();
            DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58(params, wif);
            ECKey ecKey = dumpedPrivateKey.getKey();

            // 获取私钥的BigInteger表示（十进制）
            BigInteger privateKey = ecKey.getPrivKey();

            return privateKey.toString();

        } catch (Exception e) {
            throw new RuntimeException("Failed to decode WIF: " + e.getMessage(), e);
        }
    }

    public static void main(String[] args) throws Exception {
//        System.out.println("34527361577724363799825441021785580616839584367806955738801049535146863574925".length());
////        System.out.println("Bitcoin Address: " + ecKey.toAddress(params));
//
//        BigInteger mod = new BigInteger("115792089237316195423570985008687907852837564279074904382605163141518161494337");
//
//        BigInteger modBan = mod.divide(new BigInteger("2"));
//
//        System.out.println(modBan);
//
//        System.out.println(mod.compareTo(modBan));

//        BigInteger mod2 =
//        URL url = new URL("https://www.baidu.com/");
//        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//        conn.setRequestMethod("GET");
//        BufferedReader in = new BufferedReader(
//                new InputStreamReader(conn.getInputStream()));
//        String inputLine;
//        StringBuilder response = new StringBuilder();
//
//        while ((inputLine = in.readLine()) != null) {
//            response.append(inputLine);
//        }
//        in.close();
//        System.out.println(response.toString());
//        String address = "17293V1nLJdXopG67VG9Xb7yzA2CharTsu";
//        System.out.println("地址有效性: " + BlockchainBalanceChecker.isValidBitcoinAddress(address));


//        BigInteger a = BigInteger.valueOf(10);
//        BigInteger b = BigInteger.ONE;
//        System.out.println(b.compareTo(a));

        Set<String> addresses = new HashSet<>();
        Set<String> addressesSys = new HashSet<>();
//        System.out.println("113033766253475089613203927905000344652731022895621160804587495995314555388429".length());
        BigInteger aa = new BigInteger("113033766253475089613203927905000344652731022895621160804587495995314555388441");
                   aa = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141",16).subtract(BigInteger.valueOf(8));
//        System.out.println(""+aa.length());
        for(int i =0;i<100000000;i++){
//            BitcoinPrivateKeyGenerator1.BitcoinPrivateKey privateKey = BitcoinPrivateKeyGenerator1.generatePrivateKey(new BigInteger("17032949990367614177003573183494038047605719572652609198325941622091608827023"),BigInteger.ONE);
            BitcoinPrivateKeyGenerator1.BitcoinPrivateKey privateKey = BitcoinPrivateKeyGenerator1.generatePrivateKeyDe(aa,"999999901",BigInteger.valueOf(999999907));
            aa = privateKey.getPrivateKey().multiply(new BigInteger("999999901")).divide(BigInteger.valueOf(999999907));

//            aa = aa.add(BigInteger.valueOf(1));
            if (BitcoinPrivateKeyGenerator1.isValidPrivateKey(privateKey.getPrivateKey())) {  //私钥正确的话
            // 私钥转公钥
            String wifPrivateKey = privateKey.getWIFCompressed();

            KeyPair wifKeyPair = null;
            try {
                wifKeyPair = BitcoinKeyConverter.generateFromWIF(wifPrivateKey);
            } catch (Exception e) {

            }
            String address = wifKeyPair.getLegacyAddress(); // 比特币创始区块地址公钥地址1开头
            addresses.add(wifKeyPair.getSegwitAddress());
            addresses.add(address);
            ECKey ecKey = DumpedPrivateKey.fromBase58(MAINNET, wifPrivateKey).getKey();
            // Bech32 (3开头)
            try {


                Script p2wpkhScript = ScriptBuilder.createP2WPKHOutputScript(ecKey);
                Script p2shScript = ScriptBuilder.createP2SHOutputScript(p2wpkhScript);
                String p2sh = LegacyAddress.fromScriptHash(MAINNET, p2shScript.getPubKeyHash()).toString();  // 3开头
                addresses.add(p2sh);



            }catch (Exception e){

            }



            addressesSys.add(wifPrivateKey);

            //生成5开头的地址
            NetworkParameters network = MainNetParams.get();
            DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58(network, privateKey.getWIFUncompressed());

            ECKey ecKey1 = dumpedPrivateKey.getKey();

            // 生成地址
            Address legacyAddress = LegacyAddress.fromKey(network, ecKey1);
            addresses.add(legacyAddress.toString());
            addressesSys.add(privateKey.getWIFUncompressed());

        }
        if (addresses.size() >= 300){
//            List<String> list = new ArrayList<>();
//            list.addAll(addresses);
            List<String> list = new ArrayList<>();
            list.addAll(addresses);

            String result = BlockchainBalanceChecker.getBalanceForAddresses(list);
            for(int l=0 ;result==null;l++){

                result = BlockchainBalanceChecker.getBalanceForAddresses(list);
                if(result==null && BlockchainBalanceChecker.getBaiduUrl()==null){System.exit(1);}
                if(l>=100 && result==null){
//                    fileUtils.writeFile("sy:"+sy,logPath);
//                    fileUtils.writeFile("公钥："+addresses+"\n私钥："+addressesSys+"\n",gyPath);
                    break;
                }

            }
            if(result==null){   addressesSys.clear();
                addresses.clear();  continue;}


            JSONObject jsonResponse = new JSONObject(result);
            for(String address : addresses){
                JSONObject addressInfo = jsonResponse.getJSONObject(address);
//                    System.out.println(address+":    "+addressInfo);
                Long maney = addressInfo.getLong("final_balance");
//                Long maney1 = addressInfo.getLong("final_balance1");
//                long total_received = addressInfo.getLong("total_received");
//                long jiaoyiliang = addressInfo.getLong("n_tx");
                if (maney > 0) {
//                        System.out.println("=======金额======" + maney + "私钥：" + addressesSys);

                    Bituse bituse = new Bituse();
                    bituse.setWifsy(addressesSys.toString());
                    bituse.setMask(maney+"");
//                    bituseMapper.insert(bituse);
                    System.out.println("=======金额======" + maney + "私钥：" + addressesSys);
                    if(maney>0){
                        SendEmailToQQ sendEmailToQQ = new SendEmailToQQ();
                        sendEmailToQQ.sendEmail("2267457055@qq.com","金额:"+maney+"有效值："+addressesSys);
                        System.out.println();
                        int a = 0;
                        System.out.println("a");
                    }
//                    fileUtils.writeFile( "有效值："+addressesSys+"\n",path);
                }

            }
            log.info("test:"+aa);
//            String addressString = String.join("|", addresses);
            System.out.println("公钥："+addresses);
            System.out.println("私钥："+addressesSys);

            addresses.clear();
            addressesSys.clear();
        }
        }
    }

}
